package com.lanou3g.multi_mybatis.configuration;

import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.SqlSessionTemplate;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.autoconfigure.jdbc.DataSourceBuilder;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;

import javax.sql.DataSource;

@Configuration
@MapperScan(basePackages = "com.lanou3g.multi_mybatis.mapper.lanou", sqlSessionTemplateRef  = "lanouSqlSessionTemplate")
public class LanouDataSourceConf {

	@Primary
	@Bean("lanouDataSource")
	@ConfigurationProperties(prefix = "spring.datasource.lanou")
	public DataSource lanouDataSource() {
		return DataSourceBuilder.create().build();
	}

	@Bean("lanouSessionFactory")
	public SqlSessionFactory lanouSqlSessionFactory() throws Exception {
		SqlSessionFactoryBean factoryBean = new SqlSessionFactoryBean();
		factoryBean.setDataSource(lanouDataSource());
		factoryBean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath:/mapper/lanou/*.xml"));
		return factoryBean.getObject();
	}

	@Bean("lanouTxManager")
	public DataSourceTransactionManager lanouTxMananger() {
		return new DataSourceTransactionManager(lanouDataSource());
	}

	@Bean("lanouSqlSessionTemplate")
	public SqlSessionTemplate lanouSqlSessionTempate() throws Exception {
		return new SqlSessionTemplate(lanouSqlSessionFactory());
	}
}
